<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2024/3/19} {13:57}
 */

namespace wanghua\general_utility_tools_php\coin;



use wanghua\general_utility_tools_php\http\Curl;

class Coin
{

    public $apiKey = 'f94a2a9c-28be-47c3aaa-9c29-1e83b309d076';
    public $url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';


    /**
     * desc：
    'limit'=>'1000',
    'sort'=>'market_cap',
    'sort_dir'=>'desc',
     * @param array $params
     * @return array|bool|int|string
     */
    function getAll(array $params){
        $params_str = http_build_query($params);
        $url = $this->url.'?'.$params_str;

        $header = [
            'X-CMC_PRO_API_KEY:'.$this->apiKey,
            'accept: application/json',
        ];

        return Curl::curl_get($url,10,$header);
    }


    /**
     * desc：
     *
     *https://coinmarketcap.com/api/documentation/v1/#section/Introduction
     * 'https://pro-api.coinmarketcap.com/v2/cryptocurrency/ohlcv/historical'
     * author：wh
     */
    function k(){
        $url = $this->url;
        $time_start = input('time_start');
        $time_end = input('time_end');
        $type = input('type');

        $header = [
            'X-CMC_PRO_API_KEY:'.$this->apiKey,
        ];

        $arr = explode('=',$type);
        $params = [
            $arr[0]=>$arr[1],//币种
            'time_start'=>$time_start,
            'time_end'=>$time_end,
            'count'=>7,
        ];

        $url = $url.'?'.http_build_query($params);

        return Curl::curl_get($url,10,$header);
    }

    private function curl_request($url, $method = 'GET',$data=null,$header=array(),$call_back=null)
    {
        set_time_limit(30);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if($header){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        if($method == 'POST'){
            if($data) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($call_back){
            curl_setopt($ch, CURLOPT_WRITEFUNCTION, $call_back);
        }
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            return [
                'status' => 'error',
                'message' => 'curl 错误信息: ' . curl_error($ch)
            ];
        }
        curl_close($ch);
        return $result;
    }

}